﻿/*
 * @autor: hectorea
 * @date: 11/08/2012
 * @programming interview 5
 * 
 */

namespace IsAnagram
{
    internal static class StringExtension
    {
        /// <summary>
        /// Verify is two words are anagrams
        /// </summary>
        /// <param name="input">Input string</param>
        /// <param name="anagram">Possible anagram</param>
        /// <returns>True if the two word are anagrams</returns>
        public static bool IsAnagram(this string input, string anagram)
        {
            if (input.Length != anagram.Length)
                return false;

            string s1 = BubbleSort(input);
            string s2 = BubbleSort(anagram);

            for (int i = 0; i < s1.Length; i++)
            {
                if (s1[i] != s2[i])
                    return false;
            }

            return true;
        }
        private static string BubbleSort(string input)
        {
            char[] result = input.ToCharArray();

            for (int i = 0; i < input.Length; i++)
            {
                for (int j = i; j < input.Length; j++)
                {
                    if (input[i] > input[j])
                    {
                        result[i] ^= result[j];
                        result[j] ^= result[i];
                        result[i] ^= result[j];
                    }
                }
            }

            return new string(result);
        }

        public static bool ASCIIBasedSolution(this string input, string anagram)
        {
            if (input.Length <= 0 || anagram.Length <= 0)
                return false;
            if (input.Length != anagram.Length)
                return false;

            //I'm assuming the string could be any char represented in the ASCII Table
            int[] alphabet = new int[256];

            //Store every char and increment in one every repetition
            for (int i = 0; i < input.Length; i++)
            {
                alphabet[input[i]]++;
                alphabet[anagram[i]]--;
            }
                
            
            for (int i = 0; i < alphabet.Length; i++)
            {
                if (alphabet[i] != 0)
                    return false;
            }

            return true;
        }      
    }
}
